<!--  -->
<template>
  <div>
    <el-card
      class="flex-col"
      body-style="display: flex;  flex-direction: column;  flex: 1; overflow: hidden;"
    >
      <el-descriptions title="采集变量" size="medium"></el-descriptions>
      <el-form :inline="true">
        <el-form-item label="变量名:"
          ><el-input placeholder="请输入" v-model="alias"></el-input
        ></el-form-item>
        <el-form-item label="变量地址:"
          ><el-input placeholder="请输入" v-model="name"></el-input
        ></el-form-item>
        <el-form-item label="监控状态:">
          <el-select placeholder="请选择" v-model="isMonitored">
            <el-option key="0" label="全部" :value="0"></el-option>
            <el-option key="1" label="未监控" :value="1"></el-option>
            <el-option key="2" label="监控" :value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否设置清洗:">
          <el-select placeholder="请选择" v-model="isCleaned">
            <el-option key="0" label="全部" :value="0"></el-option>
            <el-option key="1" label="否" :value="1"></el-option>
            <el-option key="2" label="是" :value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="
              () => {
                selectPlcVar();
              }
            "
            >搜索</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="
              () => {
                addPlcVarFunc();
              }
            "
            >添加</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="openCSV(node.StructGuid, node.DisplayName)"
            >导出</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="
              () => {
                importVisable = true;
                importType = 'plc';
                importBtn = false;
                fileList = [];
              }
            "
            >导入</el-button
          >
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="DeleteAllVar()">删除</el-button>
        </el-form-item>
        <el-form-item>
          <el-button
            type="warning"
            @click="
              () => {
                monitoredForm = {
                  Title: '',
                  scanPeriod: 1,
                  isMonitored: true,
                };
                $confirm(
                  `此操作加入监控
                      , 是否继续?`,
                  '提示',
                  {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                  }
                ).then(() => {
                  if (
                    this.fahtherChecked.length == 0 &&
                    this.sonChecked.length == 0
                  ) {
                    this.$message.error('请至少选择一个变量');
                    return;
                  }
                  monitoredForm.Title = '加入监控';
                  alladdMonitoredVisable = true;
                });
              }
            "
            >加入监控</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button
            type="warning"
            @click="
              () => {
                monitoredForm = {
                  Title: '',
                  scanPeriod: 1,
                  isMonitored: false,
                };
                $confirm(
                  `此操作取消监控
                      , 是否继续?`,
                  '提示',
                  {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                  }
                ).then(() => {
                  // if (this.fahtherChecked.length == 0 && this.sonChecked.length == 0) {
                  //     this.$message.error('至少选择一个变量')
                  //     return;
                  //   }
                  monitoredForm.Title = '取消监控';
                  AllAddMonitored(monitoredForm);
                });
              }
            "
            >取消监控</el-button
          >
        </el-form-item>
        <el-form-item
          ><el-button class="el-button--select" @click="ExpandList"
            >即时查看</el-button
          ></el-form-item
        >
      </el-form>
      <!-- 采集变量table -->
      <div style="flex: 1; position: relative">
        <el-table
          :row-class-name="getRowClass"
          :row-key="getRowKeys"
          :virtual-scroll="true"
          :item-size="50"
          width="100%"
          height="100%"
          ref="multipleTable"
          :data="plcValTable"
          tooltip-effect="dark"
          :highlight-current-row="true"
          :expand-row-keys="expandedRowKeys"
          @select="checkedBoxHandler"
          @select-all="fatherSelectAllHandler"
          @selection-change="handleSelectionChange"
          @expand-change="
            (row, expandedRows) => {
              expandValue(row, expandedRows);
            }
          "
          style="position: absolute; width: 100%"
        >
          <el-table-column
            type="selection"
            :reserve-selection="true"
            width="55"
          ></el-table-column>
          <!--   <el-table-column type="expand">
            <template slot-scope="props">
              <RecycleScroller
                style="height: 200px"
                class="scroller"
                :items="expandArray[0]"
                :item-size="32"
                key-field="Alias"
                v-slot="{ item }"
              >
                <div class="user">
                  {{ item.Alias }}
                </div>
              </RecycleScroller>
            </template>
          </el-table-column> -->
          <el-table-column type="expand">
            <template slot-scope="props">
              <div style="height: 400px">
                <el-table
                  v-loading="expandLoading"
                  row-key="Alias"
                  :ref="'sontable' + props.row.ID"
                  style="width: 100%"
                  :data="getRowExpandData(props.row.ID, expandArray)"
                  :show-header="true"
                  height="100%"
                  max-height="400px"
                  @selection-change="sonHandleSelectionChange"
                >
                  <el-table-column
                    type="selection"
                    width="55"
                  ></el-table-column>
                  <el-table-column width="100"></el-table-column>
                  <el-table-column prop="Alias" label="变量名" width="180">
                  </el-table-column>
                  <!-- <el-table-column prop="Name" label="变量地址" width="180">
                  </el-table-column> -->
                  <el-table-column prop="DataType" label="变量类型" width="100">
                    <template slot-scope="scope">
                      <span>{{ dataToPlc(scope.row.DataTypeId) }}</span>
                    </template>
                  </el-table-column>

                  <el-table-column prop="IsArray" label="读写类型" width="100">
                    <template slot-scope="scope">
                      <span>{{ scope.row.IsRw ? "可读写" : "只读" }}</span>
                    </template>
                  </el-table-column>
                  <!-- <el-table-column prop="IsArray" label="是否数组" width="100">
                    <template slot-scope="scope">
                      <span>{{
                        scope.row.IsArray ? "一维数组" : "标量变量"
                      }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="ArrayLength"
                    label="数组长度"
                    width="150"
                  >
                    <template slot-scope="scope">
                      <span v-if="scope.row.IsArray">{{
                        scope.row.ArrayLength
                      }}</span>
                      <span v-else>-</span>
                    </template>
                  </el-table-column> -->
                  <el-table-column
                    prop="Description"
                    label="变量描述"
                    show-overflow-tooltip
                    width="auto"
                  >
                  </el-table-column>
                  <el-table-column
                    prop="IsMonitored"
                    label="监控状态"
                    width="120"
                  >
                    <template slot-scope="scope">
                      <span v-if="!scope.row.IsArray">{{
                        scope.row.IsMonitored ? "是" : "否"
                      }}</span>
                      <span v-else>-</span>
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="ScanPeriod"
                    label="扫描周期(ms)"
                    show-overflow-tooltip
                    width="120"
                  >
                    <template slot-scope="scope">
                      <span>{{
                        scope.row.IsArray
                          ? "-"
                          : displayScanPeriod(scope.row.ScanPeriod)
                      }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="IsCleaned"
                    label="是否设置清洗"
                    show-overflow-tooltip
                    width="120"
                  >
                  </el-table-column>
                  <el-table-column
                    prop="UpdateDate"
                    label="更新时间"
                    show-overflow-tooltip
                    width="180"
                  >
                  </el-table-column>
                  <el-table-column label="操作" width="300">
                    <template slot-scope="scope">
                      <el-button
                        v-show="scope.row.IsArray != null"
                        type="text"
                        @click="
                          () => {
                            updatePlcVarFunc(scope);
                          }
                        "
                        >修改</el-button
                      >
                      <el-button
                        v-show="scope.row.IsArray != null"
                        type="text"
                        @click="
                          () => {
                            DeletePlcVar(scope.row.ID);
                          }
                        "
                        >删除</el-button
                      >
                      <el-button
                        v-show="scope.row.IsArray == false"
                        type="text"
                        @click="
                          () => {
                            var param = scope.row;

                            $confirm(
                              `此操作${
                                param.IsMonitored ? '取消监控' : '加入监控'
                              }, 是否继续?`,
                              '提示',
                              {
                                confirmButtonText: '确定',
                                cancelButtonText: '取消',
                                type: 'warning',
                              }
                            )
                              .then(() => {
                                monitoredForm = {
                                  Alias: param.Alias.split('[')[0],
                                  Update: false,
                                  Url: '',
                                  id: param.ParentId,
                                  index: 0,
                                  scanPeriod: param.ScanPeriod
                                    ? param.ScanPeriod
                                    : 1,
                                  desc: param.Description,
                                  isMonitored: !param.IsMonitored,
                                };
                                monitoredForm.Url =
                                  '/EqManage/UpdatePlcVarMonitor';
                                monitoredForm.Title = param.IsMonitored
                                  ? '取消监控'
                                  : '加入监控';
                                if (!param.IsMonitored) {
                                  addMonitoredVisable = true;
                                } else {
                                  AddMonitored(monitoredForm);
                                }
                              })
                              .catch(() => {
                                $message({
                                  type: 'info',
                                  message: `已取消操作`,
                                });
                              });
                          }
                        "
                        >{{
                          scope.row.IsMonitored ? "取消监控" : "加入监控"
                        }}</el-button
                      >

                      <el-button
                        type="text"
                        v-show="scope.row.IsArray == null"
                        @click="
                          () => {
                            arrayUpdateForm = {
                              Update: true,
                              Title: '修改数组描述',
                              Url: '/EqManage/UpdatePlcArrayDesc',
                              alias: scope.row.Alias,
                              id: scope.row.ParentId,
                              desc: scope.row.Description,
                              index: parseInt(
                                scope.row.Alias.match(/\[(.*?)\]/)[1]
                              ),
                            };
                            arrayUpdateVisable = true;
                          }
                        "
                        >修改</el-button
                      >
                      <el-button
                        v-show="scope.row.IsArray == null"
                        type="text"
                        @click="
                          () => {
                            var param = scope.row;
                            $confirm(
                              `此操作${
                                param.IsMonitored ? '取消监控' : '加入监控'
                              }, 是否继续?`,
                              '提示',
                              {
                                confirmButtonText: '确定',
                                cancelButtonText: '取消',
                                type: 'warning',
                              }
                            )
                              .then(() => {
                                monitoredForm = {
                                  Alias: param.Alias.split('[')[0],
                                  Update: true,
                                  Url: '',
                                  id: param.ParentId,
                                  index: parseInt(
                                    param.Alias.match(/\[(.*?)\]/)[1]
                                  ),
                                  scanPeriod: param.ScanPeriod
                                    ? param.ScanPeriod
                                    : 1,
                                  desc: param.Description,
                                  isMonitored: !param.IsMonitored,
                                };
                                monitoredForm.Url =
                                  '/EqManage/UpdatePlcVarMonitor';
                                monitoredForm.Title = param.IsMonitored
                                  ? '取消监控'
                                  : '加入监控';
                                if (!param.IsMonitored) {
                                  addMonitoredVisable = true;
                                } else {
                                  AddMonitored(monitoredForm);
                                }
                              })
                              .catch(() => {
                                $message({
                                  type: 'info',
                                  message: `已取消操作`,
                                });
                              });
                          }
                        "
                        >{{
                          scope.row.IsMonitored ? "取消监控" : "加入监控"
                        }}</el-button
                      >
                      <el-button
                        v-show="scope.row.IsArray == null"
                        type="text"
                        @click="GetCleanScript(scope.row, true)"
                        >清洗设置</el-button
                      >
                    </template>
                  </el-table-column>
                </el-table>
                <el-pagination
                  style="position: relative; width: 100%"
                  background
                  layout="->,total,prev, pager, next,jumper"
                  :total="sonTotal"
                  v-if="sonTotal > 0"
                  :current-page.sync="sonPageNum"
                  @current-change="handleCurrentChange"
                >
                </el-pagination>
              </div>
            </template>
          </el-table-column>

          <el-table-column type="index" label="序号" show-overflow-tooltip>
          </el-table-column>
          <el-table-column
            prop="Alias"
            label="变量名"
            width="180"
            show-overflow-tooltip
          >
          </el-table-column>
          <!-- <el-table-column
            prop="Name"
            label="变量地址"
            width="180"
            show-overflow-tooltip
          >
          </el-table-column> -->
          <el-table-column prop="DataType" label="变量类型" width="100">
            <template slot-scope="scope">
              <span>{{ dataToPlc(scope.row.DataTypeId) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="IsArray" label="读写类型" width="100">
            <template slot-scope="scope">
              <span>{{ scope.row.IsRw ? "可读写" : "只读" }}</span>
            </template>
          </el-table-column>
          <!-- <el-table-column prop="IsArray" label="是否数组" width="100">
            <template slot-scope="scope">
              <span>{{ scope.row.IsArray ? "一维数组" : "标量变量" }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="ArrayLength" label="数组长度" width="150">
            <template slot-scope="scope">
              <span v-if="scope.row.IsArray">{{ scope.row.ArrayLength }}</span>
              <span v-else>-</span>
            </template>
          </el-table-column> -->
          <el-table-column
            prop="Description"
            label="变量描述"
            show-overflow-tooltip
            width="auto"
          >
          </el-table-column>
          <el-table-column prop="IsMonitored" label="监控状态" width="120">
            <template slot-scope="scope">
              <span v-if="!scope.row.IsArray">{{
                scope.row.IsMonitored ? "是" : "否"
              }}</span>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="ScanPeriod"
            label="扫描周期(ms)"
            show-overflow-tooltip
            width="120"
          >
            <template slot-scope="scope">
              <span>{{
                scope.row.IsArray
                  ? "-"
                  : displayScanPeriod(scope.row.ScanPeriod)
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="IsCleaned"
            label="是否设置清洗"
            show-overflow-tooltip
            width="120"
          >
          </el-table-column>
          <el-table-column
            prop="UpdateDate"
            label="更新时间"
            show-overflow-tooltip
            width="180"
          >
          </el-table-column>
          <el-table-column label="操作" width="300">
            <template slot-scope="scope">
              <el-button
                v-show="scope.row.IsArray != null"
                type="text"
                @click="
                  () => {
                    updatePlcVarFunc(scope);
                  }
                "
                >修改</el-button
              >
              <el-button
                v-show="scope.row.IsArray != null"
                type="text"
                @click="
                  () => {
                    DeletePlcVar(scope.row.ID);
                  }
                "
                >删除</el-button
              >
              <el-button
                v-show="scope.row.IsArray == false"
                type="text"
                @click="
                  () => {
                    var param = scope.row;

                    $confirm(
                      `此操作${
                        param.IsMonitored ? '取消监控' : '加入监控'
                      }, 是否继续?`,
                      '提示',
                      {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning',
                      }
                    )
                      .then(() => {
                        monitoredForm = {
                          Alias: param.Alias.split('[')[0],
                          Update: false,
                          Url: '',
                          id: param.ID,
                          index: 0,
                          scanPeriod: param.ScanPeriod ? param.ScanPeriod : 1,
                          desc: param.Description,
                          isMonitored: !param.IsMonitored,
                        };
                        monitoredForm.Url = '/EqManage/UpdatePlcVarMonitor';
                        monitoredForm.Title = param.IsMonitored
                          ? '取消监控'
                          : '加入监控';
                        if (!param.IsMonitored) {
                          addMonitoredVisable = true;
                        } else {
                          AddMonitored(monitoredForm);
                        }
                      })
                      .catch((err) => {
                        $message({
                          type: 'info',
                          message: `已取消操作${err}`,
                        });
                      });
                  }
                "
                >{{
                  scope.row.IsMonitored ? "取消监控" : "加入监控"
                }}</el-button
              >

              <el-button
                type="text"
                v-show="scope.row.IsArray == null"
                @click="
                  () => {
                    arrayUpdateForm = {
                      Update: true,
                      Title: '修改数组描述',
                      Url: '/EqManage/UpdatePlcArrayDesc',
                      alias: scope.row.Alias,
                      id: scope.row.ParentId,
                      desc: scope.row.Description,
                      index: parseInt(scope.row.Alias.match(/\[(.*?)\]/)[1]),
                    };
                    arrayUpdateVisable = true;
                  }
                "
                >修改</el-button
              >
              <el-button
                v-show="scope.row.IsArray == null"
                type="text"
                @click="
                  () => {
                    var param = scope.row;
                    testConsole(param);
                    $confirm(
                      `此操作${
                        param.IsMonitored ? '取消监控' : '加入监控'
                      }, 是否继续?`,
                      '提示',
                      {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning',
                      }
                    )
                      .then(() => {
                        monitoredForm = {
                          Alias: param.Alias.split('[')[0],
                          Update: true,
                          Url: '',
                          id: param.ID,
                          index: parseInt(param.Alias.match(/\[(.*?)\]/)[1]),
                          scanPeriod: param.ScanPeriod ? param.ScanPeriod : 1,
                          desc: param.Description,
                          isMonitored: !param.IsMonitored,
                        };
                        monitoredForm.Url = '/EqManage/UpdatePlcVarMonitor';
                        monitoredForm.Title = param.IsMonitored
                          ? '取消监控'
                          : '加入监控';
                        if (!param.IsMonitored) {
                          addMonitoredVisable = true;
                        } else {
                          AddMonitored(monitoredForm);
                        }
                      })
                      .catch((err) => {
                        $message({
                          type: 'info',
                          message: `已取消操作${err}`,
                        });
                      });
                  }
                "
                >{{
                  scope.row.IsMonitored ? "取消监控" : "加入监控"
                }}</el-button
              >
              <el-button
                v-show="scope.row.IsArray == false"
                type="text"
                @click="GetCleanScript(scope.row, false)"
                >清洗设置</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>

      <el-pagination
        background
        layout="->,total,sizes,prev, pager, next,jumper"
        :total="total"
        v-if="total > 0"
        :current-page.sync="pageNum"
        :page-sizes="[20, 40, 60, 100]"
        :page-size="pageSize"
        @size-change="handleSizeChange"
        @current-change="fatherCurrentChange"
      >
      </el-pagination>

      <!-- 添加采集变量弹窗 -->
      <el-dialog
        @open="openDialog('plcVarFormRef')"
        destroy-on-close
        :visible.sync="plcVarVisable"
        width="30%"
      >
        <span slot="title" style="text-align: center"
          >{{ plcVarForm.Title }}
          <el-divider></el-divider>
        </span>
        <el-form
          ref="plcVarFormRef"
          :model="plcVarForm"
          :rules="globalRules"
          label-width="200px"
        >
          <el-form-item prop="alias" label="变量名">
            <el-input
              v-model="plcVarForm.alias"
              style="width: 50%"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item prop="isRw" label="读写类型">
            <el-radio-group v-model="plcVarForm.isRw">
              <el-radio :label="0">只读</el-radio>
              <el-radio :label="1">可读写</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item prop="name" label="变量地址">
            <el-input
              v-model="plcVarForm.name"
              style="width: 50%"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="变量类型" required>
            <el-select
              style="width: 50%"
              v-model="plcVarForm.dataTypeId"
              placeholder="请选择变量类型"
            >
              <el-option
                v-for="item in variableType"
                :key="item.name"
                :label="item.name"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="是否数组" required>
            <el-select
              style="width: 50%"
              v-model="plcVarForm.isArray"
              placeholder="请选择数据类型"
              @change="
                () => {
                  plcVarForm.arrayLength = 0;
                }
              "
            >
              <el-option label="标量变量" :value="false"></el-option>
              <el-option label="一维数组" :value="true"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            v-show="plcVarForm.isArray"
            prop="arrayLength"
            label="数组长度"
          >
            <!-- <el-input-number 
          v-model="plcVarForm.arrayLength" 
          controls-position="right"  
          :min="1" 
          :step="1"
          ></el-input-number> -->
            <el-input
              type="number"
              v-model.number="plcVarForm.arrayLength"
              style="width: 50%"
              :control="false"
              :value-on-clear="1"
              oninput="value=parseInt(value.replace(/[^\d]/g,''))"
              autocomplete="off"
              :min="1"
            ></el-input>
          </el-form-item>

          <el-form-item label="变量描述">
            <el-input
              v-model="plcVarForm.description"
              style="width: 50%"
              autocomplete="off"
            ></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer" style="text-align: center">
          <el-divider></el-divider>
          <div>
            <el-button
              @click="
                () => {
                  plcVarVisable = false;
                }
              "
              >取 消</el-button
            >
            <el-button
              type="primary"
              @click="
                () => {
                  addPlcVar(plcVarForm);
                }
              "
              >确 定</el-button
            >
          </div>
        </span>
      </el-dialog>

      <el-dialog
        destroy-on-close
        :visible.sync="addMonitoredVisable"
        width="30%"
        @open="openDialog('monitoredForm')"
      >
        <span slot="title" style="text-align: center"
          >{{ monitoredForm.Title }}
          <el-divider></el-divider>
        </span>
        <el-form
          :model="monitoredForm"
          :rules="dialogRules"
          ref="monitoredForm"
          label-width="200px"
        >
          <el-form-item label="扫描周期(ms)" prop="scanPeriod">
            <el-input
              type="number"
              style="width: 30%"
              v-model="monitoredForm.scanPeriod"
            ></el-input>
            <label> *100</label>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer" style="text-align: center">
          <el-divider></el-divider>
          <div>
            <el-button @click="addMonitoredVisable = false">取 消</el-button>
            <el-button
              type="primary"
              @click="
                () => {
                  AddMonitored(monitoredForm);
                }
              "
              >确 定</el-button
            >
          </div>
        </span>
      </el-dialog>

      <el-dialog
        destroy-on-close
        :visible.sync="arrayUpdateVisable"
        width="30%"
      >
        <span slot="title" style="text-align: center"
          >修改数组位变量
          <el-divider></el-divider>
        </span>
        <el-form :model="arrayUpdateForm" label-width="200px">
          <el-form-item label="变量名">
            <label> {{ arrayUpdateForm.alias }}</label>
          </el-form-item>
          <el-form-item label="变量描述">
            <el-input
              v-model="arrayUpdateForm.desc"
              style="width: 50%"
              autocomplete="off"
            ></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer" style="text-align: center">
          <el-divider></el-divider>
          <div>
            <el-button @click="arrayUpdateVisable = false">取 消</el-button>
            <el-button
              type="primary"
              @click="
                () => {
                  UpdateArrayDescript(arrayUpdateForm);
                  arrayUpdateVisable = false;
                }
              "
              >确 定</el-button
            >
          </div>
        </span>
      </el-dialog>

      <el-dialog destroy-on-close :visible.sync="importVisable" width="30%">
        <span slot="title" style="text-align: center"
          >导入采集变量
          <el-button
            type="text"
            style="margin-left: 450px"
            @click="DownLoadTemplate"
            >下载模板</el-button
          >
          <el-divider></el-divider>
          <el-upload
            class="upload-demo"
            :auto-upload="false"
            :file-list="fileList"
            ref="upload"
            drag
            action=""
            :on-change="addfile"
            multiple
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <div class="import-icon" slot="tip">
              <i style="color: red" class="el-icon-warning-outline"></i>
              <span>导入时,将对目标对象的采集变量进行全覆盖,请知悉!</span>
            </div>
          </el-upload>
          <span slot="footer" class="dialog-footer" style="text-align: center">
            <el-divider></el-divider>
            <div>
              <el-button
                @click="
                  () => {
                    importVisable = false;
                  }
                "
                >取 消</el-button
              >
              <el-button
                :disabled="!importBtn"
                type="primary"
                @click="
                  () => {
                    confirmImport(importType);
                  }
                "
                >确 定</el-button
              >
            </div>
          </span>
        </span>
      </el-dialog>
      <el-dialog
        destroy-on-close
        :visible.sync="alladdMonitoredVisable"
        width="30%"
        @open="openDialog('allmonitoredForm')"
      >
        <span slot="title" style="text-align: center"
          >{{ monitoredForm.Title }}
          <el-divider></el-divider>
        </span>
        <el-form
          :model="monitoredForm"
          ref="allmonitoredForm"
          label-width="200px"
          :rules="dialogRules"
        >
          <el-form-item label="扫描周期(ms)" prop="scanPeriod">
            <el-input
              type="number"
              style="width: 30%"
              v-model="monitoredForm.scanPeriod"
            ></el-input>
            <label> *100</label>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer" style="text-align: center">
          <el-divider></el-divider>
          <div>
            <el-button @click="alladdMonitoredVisable = false">取 消</el-button>
            <el-button
              type="primary"
              @click="
                () => {
                  //AddMonitored(monitoredForm);
                  AllAddMonitored(monitoredForm);
                }
              "
              >确 定</el-button
            >
          </div>
        </span>
      </el-dialog>
      <!-- 清洗设置弹窗 -->
      <el-dialog
        destroy-on-close
        :visible.sync="dataCleanSettingDialogVisable"
        width="70%"
        @close="
          () => {
            this.$refs['cleanform'].clearValidate();
            this.cleanform = {
              index: -1,
              cleanedParamName: '',
              cleanedParamId: 0,
              output: '',
              inputName: '',
              outputType: -1,
              dynamicItem: [],
              codeOutput: '',
            };
            this.dataCleanSettingDialogVisable = false;
            // 在需要清除验证状态的地方
            this.clearTableValidation();
            (this.tableDataInput = []), (this.isCodeValid = true);
          }
        "
      >
        <span slot="title">清洗规则设置</span>
        <el-divider></el-divider>
        <div style="display: flex; justify-content: flex-end">
          <el-button
            style="margin-bottom: 5px; margin-right: 20px; margin-left: auto"
            size="medium"
            type="text"
            @click="clearCleanDialog"
            >清空</el-button
          >
        </div>
        <div>
          <el-row :gutter="20">
            <el-col :span="12" style="height: 575px">
              <div class="bordered-col" style="height: 550px; overflow: auto">
                <div>1.输入输出参数设置</div>

                <el-form
                  ref="cleanform"
                  :inline="true"
                  :model="cleanform"
                  label-width="80px"
                  label-position="right"
                >
                  <el-divider content-position="left">输入参数</el-divider>
                  <el-form-item>
                    <el-form-item
                      label="入参："
                      prop="inputName"
                      :rules="[
                        {
                          required: true,
                          message: '参数名不能为空',
                          trigger: 'blur',
                        },
                      ]"
                    >
                      <el-cascader
                        v-model="cleanform.inputName"
                        filterable
                        :options="inputAliasOptions"
                        :show-all-levels="false"
                        :props="{ emitPath: false }"
                      >
                      </el-cascader>
                    </el-form-item>
                  </el-form-item>
                  <el-button
                    @click="addItem('cleanform')"
                    icon="el-icon-circle-plus"
                  ></el-button>
                  <div class="scrollable-div">
                    <div
                      v-for="(item, index) in cleanform.dynamicItem"
                      :key="index"
                    >
                      <el-form-item
                        :label="'T' + index + ':'"
                        :prop="'dynamicItem.' + index + '.name'"
                      >
                        <el-tag
                          type="info"
                          closable
                          @close="
                            () => {
                              deleteItem(item, index);
                            }
                          "
                        >
                          {{ item.name }}
                        </el-tag>
                      </el-form-item>
                    </div>
                  </div>
                  <el-divider content-position="left">输出参数</el-divider>
                  <el-form-item
                    label="出参："
                    prop="output"
                    :rules="[
                      {
                        required: true,
                        message: '参数名不能为空',
                        trigger: 'blur',
                      },
                    ]"
                  >
                    <el-input
                      v-model="cleanform.output"
                      disabled
                      style="width: 300px"
                    ></el-input>
                  </el-form-item>
                  <el-divider content-position="left">输出类型</el-divider>
                  <el-form-item
                    label="类型："
                    prop="outputType"
                    :rules="[
                      {
                        required: true,
                        message: '输出类型不能为空',
                        trigger: 'blur',
                      },
                    ]"
                  >
                    <el-select
                      v-model="cleanform.outputType"
                      placeholder="请选择输出类型"
                    >
                      <el-option
                        v-for="item in variableType"
                        :key="item.value"
                        :label="item.name"
                        :value="item.value"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-form>
              </div>
            </el-col>
            <el-col :span="12" style="height: 575px">
              <div class="bordered-col" style="height: 550px; overflow: auto">
                <div>2.脚本内容设置</div>
                <codemirror
                  v-model="cleanform.codeInput"
                  :options="OptionCodeInput"
                ></codemirror>
              </div>
            </el-col>
          </el-row>
          <el-row class="bordered-col" style="margin-top: 10px">
            <div>调试模拟器</div>
            <el-col :span="11">
              <el-table
                :data="tableDataInput"
                style="width: 100%; overflow: auto"
                height="500"
              >
                <el-table-column prop="param" label="入参"></el-table-column>
                <el-table-column label="变量名称">
                  <template #default="{ $index }">
                    <span>T{{ $index }}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="dataType"
                  label="数据类型"
                ></el-table-column>
                <el-table-column prop="inputValue" label="输入值">
                  <template slot-scope="scope">
                    <el-form :model="scope.row">
                      <el-form-item
                        prop="inputValue"
                        :ref="'inputValue_' + scope.$index"
                        :rules="getInputValueValidationRules(scope.row)"
                        :model="'inputValue_' + scope.$index"
                      >
                        <el-input
                          v-model="scope.row.inputValue"
                          placeholder="请输入测试值"
                        ></el-input>
                      </el-form-item>
                    </el-form>
                  </template>
                </el-table-column>
              </el-table>
              <div
                style="display: flex; justify-content: center; margin-top: 10px"
              >
                <el-button
                  type="primary"
                  @click="
                    () => {
                      CleanScriptDebugging();
                    }
                  "
                  >调试</el-button
                >
              </div>
            </el-col>
            <el-col
              :span="2"
              style="
                display: flex;
                align-items: center;
                justify-content: center;
              "
            >
              <div
                style="
                  width: 0px;
                  height: 550px;
                  border: 0.5px solid rgb(215, 218, 224);
                "
              ></div>
            </el-col>

            <el-col :span="11">
              <div>输出结果：</div>
              <div
                style="
                  display: flex;
                  justify-content: center;
                  align-items: center;
                  height: 100%;
                "
              >
                <div style="width: 100%">
                  <textarea
                    style="
                      background-color: black;
                      color: white;
                      width: 100%;
                      height: 500px;
                      font-size: 12px;
                      resize: none;
                    "
                    v-model="cleanform.codeOutput"
                    readonly
                  ></textarea>
                </div>
              </div>
              <div v-if="!isCodeValid" class="error-message">
                {{ errorMessage }}
              </div>
            </el-col>
          </el-row>
        </div>
        <span slot="footer" class="dialog-footer" style="text-align: center">
          <el-divider></el-divider>
          <div>
            <el-button
              @click="
                () => {
                  this.$refs['cleanform'].clearValidate();
                  this.cleanform = {
                    index: -1,
                    cleanedParamName: '',
                    cleanedParamId: 0,
                    output: '',
                    codeOutput: '',
                    inputName: '',
                    outputType: -1,
                    dynamicItem: [],
                  };
                  this.dataCleanSettingDialogVisable = false;
                  // 在需要清除验证状态的地方
                  this.clearTableValidation();
                  (this.tableDataInput = []), (this.isCodeValid = true);
                }
              "
              >取 消</el-button
            >
            <el-button
              type="primary"
              @click="
                () => {
                  saveCleanRuleBaseInfoCheck();
                }
              "
              >确 定</el-button
            >
          </div>
        </span>
      </el-dialog>
      <el-dialog
        destroy-on-close
        :visible.sync="selectView"
        width="50%"
        @close="DeleteRealPlcVar"
      >
        <span slot="title" style="text-align: center"
          >即时查看变量
          <el-divider></el-divider>
          <el-table
            header-fixed
            ref="monitorTable"
            v-loading="monitorLoading"
            class="table-border"
            :height="700"
            :data="varTableData"
            style="width: 100%; overflow: auto"
          >
            <el-table-column prop="Name">
              <template #header>
                <span style="margin-right: 10px">变量</span>
                <el-popover
                  placement="bottom"
                  width="300"
                  trigger="click"
                  popper-class="filter-table-input"
                  ref="popoverMonitor"
                  @hide="
                    () => {
                      (monitorDataTree = [
                        {
                          id: 1,
                          label: '全选',
                          children: [],
                        },
                      ]),
                        (monitorDataTree[0].children = varTableDataAlways.map(
                          (item) => ({
                            id: item.Name,
                            label: item.Name,
                          })
                        ));
                      filterText = '';
                      $refs.tree.setCheckedKeys(defaultCheckedKeys);
                      monitorFilterNameChecked = monitorDataTree[0].children
                        .filter((item) => defaultCheckedKeys.includes(item.id))
                        .map((item) => ({
                          label: item.label,
                          id: item.id,
                        }));
                    }
                  "
                  @show="
                    () => {
                      defaultCheckedKeys = monitorFilterNameChecked.map(
                        (item) => item.id
                      );
                    }
                  "
                >
                  <i
                    slot="reference"
                    class="el-icon-s-unfold table-filter-icon"
                  />
                  <!-- content -->
                  <section class="table-filter-btns">
                    <el-input
                      placeholder="输入关键字进行过滤"
                      prefix-icon="el-icon-search"
                      v-model="filterText"
                    ></el-input>
                    <el-tree
                      class="filter-tree"
                      :default-expand-all="true"
                      :data="monitorDataTree"
                      :props="defaultProps"
                      :filter-node-method="filterNode"
                      :expand-on-click-node="false"
                      show-checkbox
                      ref="tree"
                      node-key="id"
                      @check-change="handleCheckChange"
                      :default-checked-keys="defaultCheckedKeys"
                    ></el-tree>
                    <div class="tree-footer">
                      <el-button
                        type="default"
                        @click="
                          () => {
                            $refs.popoverMonitor.doClose(); // 关闭el-popover
                          }
                        "
                        >取消</el-button
                      >
                      <el-button
                        type="primary"
                        icon="el-icon-search"
                        @click="combinedFilterHandler"
                        >筛选</el-button
                      >
                    </div>
                  </section>
                </el-popover>
              </template>
            </el-table-column>
            <el-table-column prop="Description">
              <template #header>
                <span style="margin-right: 10px">变量描述</span>
                <el-popover
                  placement="bottom"
                  width="300"
                  trigger="click"
                  popper-class="filter-table-input"
                  ref="popover"
                  @hide="
                    () => {
                      monitorDataDescTree = [
                        {
                          id: 1,
                          label: '全选',
                          children: [],
                        },
                      ];

                      const uniqueChildren = [];
                      const uniqueLabels = new Set();

                      varTableDataAlways.forEach((item) => {
                        if (!uniqueLabels.has(item.Description)) {
                          uniqueLabels.add(item.Description);
                          uniqueChildren.push({
                            id: item.Description,
                            label: item.Description,
                          });
                        }
                      });

                      monitorDataDescTree[0].children = uniqueChildren;
                      filterText2 = '';
                      $refs.tree1.setCheckedKeys(defaultCheckedKeys2);
                      monitorFilterDescChecked = monitorDataDescTree[0].children
                        .filter((item) => defaultCheckedKeys2.includes(item.id))
                        .map((item) => ({
                          label: item.label,
                          id: item.id,
                        }));
                    }
                  "
                  @show="
                    () => {
                      defaultCheckedKeys2 = monitorFilterDescChecked.map(
                        (item) => item.id
                      );
                    }
                  "
                >
                  <i
                    slot="reference"
                    class="el-icon-s-unfold table-filter-icon"
                  />
                  <!-- content -->
                  <section class="table-filter-btns">
                    <el-input
                      placeholder="输入关键字进行过滤"
                      prefix-icon="el-icon-search"
                      v-model="filterText2"
                    ></el-input>
                    <el-tree
                      class="filter-tree"
                      :default-expand-all="true"
                      :data="monitorDataDescTree"
                      :props="defaultProps"
                      :filter-node-method="filterNode"
                      :expand-on-click-node="false"
                      show-checkbox
                      ref="tree1"
                      node-key="id"
                      @check-change="handleCheckDescChange"
                      :default-checked-keys="defaultCheckedKeys2"
                    ></el-tree>
                    <div class="tree-footer">
                      <el-button
                        type="default"
                        @click="
                          () => {
                            $refs.popover.doClose(); // 关闭el-popover
                          }
                        "
                        >取消</el-button
                      >
                      <el-button
                        type="primary"
                        icon="el-icon-search"
                        @click="combinedFilterHandler"
                        >筛选</el-button
                      >
                    </div>
                  </section>
                </el-popover>
              </template>
            </el-table-column>
            <el-table-column prop="OldValue" label="当前值">
              <template slot-scope="scope">
                <span v-if="scope.row.OldValue == '?'" style="color: red">{{
                  scope.row.OldValue
                }}</span>
                <span v-else>{{ scope.row.OldValue }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="Value" label="清洗后值">
              <template slot-scope="scope">
                <span v-if="scope.row.Value == '?'" style="color: red">{{
                  scope.row.Value
                }}</span>
                <span v-else>{{ scope.row.Value }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="Time" label="耗时(ms)"> </el-table-column>
            <el-table-column prop="UpdateTime" label="最近一次读取时间">
            </el-table-column>
          </el-table>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>


<script>
import * as XLSX from "xlsx";
import JSONBig from "json-bigint";
// #region 覆盖scrollbar样式功能
import "codemirror/addon/scroll/simplescrollbars.css";
import "codemirror/addon/scroll/simplescrollbars";
import "codemirror/addon/display/placeholder.js";
// #endregion
const Stomp = require("stompjs");
import { codemirror } from "vue-codemirror";
import "codemirror/lib/codemirror.css";
import "codemirror/theme/base16-dark.css";
import "codemirror/mode/clike/clike.js";
import { isNotNumber, isPositiveInteger } from "@/utils/numberHelper.js";
import { stringify } from "json-bigint";
import $http from "../../../utils/apiHelper";
import * as $base from "../../../utils/js-base64";
export default {
  props: { node: Object },

  data() {
    const validatePeriod = (rule, value, callback) => {
      if (value === undefined || value === "") {
        callback(new Error("扫描周期不能为空"));
      }
      if (isNotNumber(value)) {
        callback(new Error("扫描周期必须为数字"));
      }
      if (!isPositiveInteger(value)) {
        callback(new Error("扫描周期必须为正整数"));
      }
      //  if (!isPositiveInteger(value / 100)) {
      //   callback(new Error("扫描周期必须为100的整数倍"));
      // }
      // if (value > 100) {
      //   callback(new Error("扫描周期必须为小于等于100"));
      // }
      callback();
    };
    const validateArray = (rule, value, callback) => {
      if (!this.plcVarForm.isArray) {
        callback();
      }
      //console.log("valute", value);
      if (value === "") {
        callback(new Error("数组长度不能为空"));
      } else if (isNotNumber(value)) {
        callback(new Error("数组长度必须为数字"));
      } else if (!isPositiveInteger(value)) {
        callback(new Error("数组长度必须为正整数"));
      }
      callback();
    };
    return {
      client: "",
      defaultCheckedKeys: [], // 保存原始的勾选状态,
      defaultCheckedKeys2: [], // 保存原始的勾选状态,
      filterText: "",
      filterText2: "",
      monitorFilterNameChecked: [],
      monitorFilterDescChecked: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
      monitorDataTree: [
        {
          id: 1,
          label: "全选",
          children: [],
        },
      ],
      monitorDataDescTree: [
        {
          id: 1,
          label: "全选",
          children: [],
        },
      ],
      varTableData: [],
      varTableDataAlways: [],
      monitorLoading: false,
      errorMessage: "", // 存储后台返回的错误信息
      selectView: false,
      isCodeValid: true,
      OptionCodeOutput: {
        // codemirror options
        tabSize: 4,
        mode: "text/x-csharp",
        lineNumbers: true,
        theme: "base16-dark",
        line: true,
        readOnly: true,
        autoRefresh: true, // 重点是这句，为true
        // more codemirror options, 更多 codemirror 的高级配置...
      },
      OptionCodeInput: {
        // codemirror options
        tabSize: 4,
        mode: "text/x-csharp",
        lineNumbers: true,
        theme: "base16-dark",
        line: true,
        placeholder: `Tips:
输入脚本、入参T0~T9完成清洗规则配置：
1）四则运算，如：return T0+T1-T2;
2）三元运算，如：return T0==1?T2:T3;
3）位截取，如：return T0.ToString("F2");
4）拼接：如：return T1+T2;
5）过滤无效值，如：if(T0 < 0){return 0;} return T0;`, // 设置提示文本
      },

      inputAliasOptions: [],
      tableDataInput: [],
      cleanform: {
        codeOutput: "",
        codeInput: "",
        index: -1,
        cleanedParamName: "",
        cleanedParamId: 0,
        output: "",
        inputName: "",
        outputType: -1,
        dynamicItem: [],
      },
      dataCleanSettingDialogVisable: false,

      expandLoading: false,
      alladdMonitoredVisable: false,
      importBtn: false,
      fileList: [],
      importVisable: false,
      sonTotal: 0,
      sonPageNum: 1,
      sonChecked: [],
      fahtherChecked: [],
      tableData: [],
      multipleSelection: [],
      fatherParam: [], //用于存储添加的元素
      sonParam: [],
      indeterminateAll: false, //指示是否全局半选
      isAllChecked: false, //指示是否全选
      indeterminate: "",
      arrayUpdateForm: "",
      arrayUpdateVisable: false,
      monitoredForm: "",
      addMonitoredVisable: false,
      globalRules: {
        alias: [
          { required: true, message: "变量名不可为空", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              const reg = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
              if (reg.test(value)) {
                callback();
              } else {
                callback(new Error("变量名不符合命名规范"));
              }
            },
            trigger: "change",
          },
        ],
        name: [
          {
            trigger: "blur",
          },
          // {
          //   validator: (rule, value, callback) => {
          //     const reg = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
          //     if (reg.test(value)) {
          //       callback();
          //     } else {
          //       callback(new Error("变量名不符合命名规范"));
          //     }
          //   },
          //   trigger: "blur",
          // },
          { required: true, message: "变量地址不可为空", trigger: "blur" },
        ],
        description: [
          { required: true, message: "变量描述不可为空", trigger: "blur" },
        ],
        arrayLength: [
          { required: true, validator: validateArray, trigger: "blur" },
        ],
      },
      plcVarVisable: false,
      textarea: "",
      plcVarForm: "",
      alias: "",
      name: "",
      isCleaned: 0,
      isMonitored: 0,
      pageNum: 1,
      pageSize: 20,
      total: 1,
      plcValTable: [],
      selectAll: false,
      variableType: [
        { name: "Boolean", value: 1 },
        { name: "SByte", value: 2 },
        { name: "Byte", value: 3 },
        { name: "Int16", value: 4 },
        { name: "UInt16", value: 5 },
        { name: "Int32", value: 6 },
        { name: "UInt32", value: 7 },
        { name: "Int64", value: 8 },
        { name: "UInt64", value: 9 },
        { name: "Float", value: 10 },
        { name: "Double", value: 11 },
        { name: "String", value: 12 },
      ],
      tstdata: "",
      expandArray: [],
      expandEvent: "",
      expandObj: "",
      searchConditionLast: {
        pageSize: 0,
        currentPage: 0,
        plcId: 0,
        alias: "",
        name: "",
        isMonitored: false,
        isCleaned: 0,
      },
      searchSonConditionLast: {
        alias: "",
        name: "",
        currPage: 0,
        id: 0,
        monitoredState: 0,
        dataType: 0,
        persistenceState: 0,
        isCleaned: false,
      },
      plcVarFormRef: {},
      monitorForm: {
        scanPeriod: 1,
      },
      allmonitoredForm: {
        scanPeriod: 1,
      },
      dialogRules: {
        scanPeriod: [
          { validator: validatePeriod, trigger: "change", required: true },
        ],
      },
      expandedRowKeys: [],
      userId: "",
    };
  },
  methods: {
    async mqtthuoquMsg() {
      const res = this.$store.state.systemconfig.system.find(
        (x) => x.ConfigName == "RabbitMq"
      );

      const settings = JSON.parse(res.Config);

      //初始化连接
      const headers = {
        login: settings.user,
        passcode: settings.passward,
      };
      this.client = Stomp.client(settings.ip);

      //this.client.onWebSocketClose
      //进行连接
      this.client.connect(
        headers.login,
        headers.passcode,
        this.onConnected,
        this.onFailed,
        "/"
      );
    },
    onConnected: function () {
      //订阅频道
      // const topic = "/exchange/Logs_exchange/SystemLog";
      const topic = "/exchange/Eap-Exchange/RealVar";

      //this.client.subscribe(topic, this.responseCallback, { id: 10010 });

      this.client.subscribe(topic, this.responseCallback, { id: 10013 });
    },
    responseCallback: function (frame) {
      console.log("MQ msg=>" + frame.body);
      //接收消息处理
      //序列化消息
      let msg = JSONBig.parse(frame.body);
      if (msg.DataSnowID && msg.IsMemberOfArray) {
        //存在说明是变量监控,且为数组
        let varData = this.varTableData.find(
          (t) =>
            t.ID == String(msg.DataSnowID) &&
            t.IsArray == msg.IsMemberOfArray &&
            t.Index == msg.ArrayIndex
        );
        if (varData) {
          varData.Value = msg.NewValue;
          varData.OldValue = msg.OldValue;
          varData.UpdateTime = this.$moment(msg.ChangeTime)
            .utcOffset("+08:00")
            .format("yyyy/MM/DD HH:mm:ss");
          varData.Time = msg.TimeConsunming;
        }
      } else if (msg.DataSnowID && !msg.IsMemberOfArray) {
        //非数组变量
        let varData = this.varTableData.find(
          (t) => t.ID == String(msg.DataSnowID)
        );
        if (varData) {
          varData.Value = msg.NewValue;
          varData.OldValue = msg.OldValue;
          varData.UpdateTime = this.$moment(msg.ChangeTime)
            .utcOffset("+08:00")
            .format("yyyy/MM/DD HH:mm:ss");
          varData.Time = msg.TimeConsunming;
        }
      }
    },
    onFailed: function (frame) {
      console.log("MQ Failed: " + frame);
      this.$message.error("连接失败");
    },
    close: function () {
      if (this.client) {
        this.client.disconnect(function () {
          console.log("已退出账号");
        });
      }
    },
    DownLoadTemplate() {
      $http
        .get(`/EqManage/DownLoadPlcVarDataTemplate`, {
          responseType: "blob",
        })
        .then((res) => {
          if (res) {
            const url = window.URL.createObjectURL(
              new Blob([res], { type: "application/vnd.ms-excel" })
            );
            const link = document.createElement("a");
            link.href = url;
            link.setAttribute("download", `plcvarTemplate.xlsx`);
            document.body.appendChild(link);
            link.click();
          } else {
            this.$message({
              type: "error",
              message: "导出部件变量失败",
            });
          }
        })
        .catch((error) => {
          //debugger;
          this.$message({
            type: "error",
            message: `${error.response.data.Message}`,
          });
        });
    },
    handleCheckChange(data, checked, indeterminate) {
      if (data.children) {
        return;
      }
      if (checked) {
        if (
          !this.monitorFilterNameChecked.some((item) => item.id === data.id)
        ) {
          this.monitorFilterNameChecked.push(data);
        }
      } else {
        const index = this.monitorFilterNameChecked.findIndex(
          (item) => item.id === data.id
        );
        if (index > -1) {
          this.monitorFilterNameChecked.splice(index, 1);
        }
      }
    },
    handleCheckDescChange(data, checked, indeterminate) {
      if (data.children) {
        return;
      }
      if (checked) {
        if (
          !this.monitorFilterDescChecked.some((item) => item.id === data.id)
        ) {
          this.monitorFilterDescChecked.push(data);
        }
      } else {
        const index = this.monitorFilterDescChecked.findIndex(
          (item) => item.id === data.id
        );
        if (index > -1) {
          this.monitorFilterDescChecked.splice(index, 1);
        }
      }
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    combinedFilterHandler() {
      this.defaultCheckedKeys = this.monitorFilterNameChecked.map(
        (item) => item.id
      );
      this.defaultCheckedKeys2 = this.monitorFilterDescChecked.map(
        (item) => item.id
      );
      this.varTableData = this.varTableDataAlways.filter((itemAlways) => {
        return (
          (this.monitorFilterDescChecked.length === 0 ||
            this.monitorFilterDescChecked.some((itemChecked) => {
              this.$refs.popoverMonitor.doClose(); // 关闭el-popover
              this.$refs.popover.doClose(); // 关闭el-popover
              return itemAlways.Description === itemChecked.label;
            })) &&
          (this.monitorFilterNameChecked.length === 0 ||
            this.monitorFilterNameChecked.some((itemChecked) => {
              this.$refs.popoverMonitor.doClose(); // 关闭el-popover
              this.$refs.popover.doClose(); // 关闭el-popover
              return itemAlways.Name === itemChecked.label;
            }))
        );
      });
    },
    reset() {
      (this.expandedRowKeys = []),
        (this.alias = ""),
        (this.name = ""),
        (this.isCleaned = 0),
        (this.isMonitored = 0);
    },
    /**
     * 在打开弹窗时清除掉表单的校验规则，不然在打开弹窗时默认会校验一次
     * @param {表单ref名} formName
     */
    openDialog(formName) {
      this.$nextTick(() => {
        this.$refs[formName].clearValidate();
      });
    },
    addPlcVarFunc() {
      this.plcVarForm = {
        Url: "",
        Title: "",
        alias: "",
        bizTypeEnum: 0,
        name: "",
        id: 0,
        plcId: this.node.StructGuid,
        isArray: false,
        arrayLength: 0,
        isMonitored: false,
        dataTypeId: 1,
        isRw: 0,
        scanPeriod: 1,
        monitorInfo: "",
        description: "",
      };

      this.plcVarForm.Url = "/EqManage/AddVar";
      this.plcVarForm.Title = "新建采集变量";
      this.plcVarVisable = true;
      if (this.$refs.plcVarForm) {
        this.$refs.plcVarForm.resetFields();
      }
    },
    updatePlcVarFunc(scope) {
      var param = scope.row;
      this.plcVarForm = {
        Url: "",
        Title: "",
        alias: param.Alias,
        bizTypeEnum: param.BizType,
        name: param.Name,
        id: param.ID,
        plcId: param.PlcID,
        isArray: param.IsArray,
        arrayLength: param.ArrayLength,
        isMonitored: param.IsMonitored,
        dataTypeId: param.DataTypeId,
        isRw: param.IsRw,
        scanPeriod: param.ScanPeriod,
        monitorInfo: param.MonitorInfo,
        description: param.Description,
      };

      this.plcVarForm.Url = "/EqManage/UpdateVar";
      this.plcVarForm.Title = "修改采集变量";
      this.plcVarVisable = true;
      if (this.$refs.plcVarForm) {
        this.$refs.plcVarForm.resetFields();
      }
    },
    ///清除清洗规则设置数据
    clearCleanDialog() {
      this.isCodeValid = true;
      this.errorMessage = "";
      (this.cleanform.codeOutput = ""),
        (this.cleanform.codeInput = ""),
        (this.cleanform.dynamicItem = this.cleanform.dynamicItem.slice(0, 1));
      this.tableDataInput[0].inputValue = "";
      let initalValue = this.tableDataInput[0];
      this.tableDataInput = [];
      this.$nextTick(() => {
        this.$refs["inputValue_0"].clearValidate();
      });
      this.tableDataInput.push(initalValue);
    },
    // 清除所有输入框的验证状态
    clearTableValidation() {
      for (
        let rowIndex = 0;
        rowIndex < this.tableDataInput.length;
        rowIndex++
      ) {
        const inputValueruleFormRef =
          this.$refs["inputValueruleForm_" + rowIndex];
        const inputValueRef = this.$refs["inputValue_" + rowIndex];
        if (inputValueruleFormRef && inputValueruleFormRef.clearValidate) {
          inputValueruleFormRef.clearValidate();
        }

        if (inputValueRef && inputValueRef.clearValidate) {
          inputValueRef.clearValidate();
        }
      }
    },
    /**
     * 清洗设置按钮
     * @param {*} row
     * @param {*} isArray
     */
    GetCleanScript(row, isArray) {
      let param = {
        Index: isArray ? row.Index : -1,
        CleanedParamId: isArray ? row.ParentId : row.ID,
        PLCID: this.node.StructGuid,
        CleanedParamName: row.Alias,
        CleanedParamType: row.DataTypeId,
      };

      $http.post(`/EqManage/GetCleanScript`, param).then((res) => {
        if (res.Status == 200) {
          this.cleanform.outputType = res.Data.OutParamInfo.OutputParamType;
          this.cleanform.output = res.Data.OutParamInfo.OutputParamName;
          this.cleanform.index = res.Data.Index;
          this.cleanform.cleanedParamId = res.Data.CleanedParamId;
          this.cleanform.cleanedParamName = res.Data.CleanedParamName;
          this.cleanform.dynamicItem = res.Data.InputParamInfos.map((item) => ({
            name: item.InputParamName,
          }));
          this.tableDataInput = res.Data.InputParamInfos.map((item) => ({
            param: item.InputParamName,
            dataType: this.variableType.find(
              (x) => x.value == item.InputParamVariableType
            ).name,
            inputValue: "",
            id: item.InputParamId,
            index: item.index,
          }));

          this.cleanform.codeInput = res.Data.ScriptContent;

          this.clearTableValidation();
          this.dataCleanSettingDialogVisable = true;
          //this.$refs.inputValueruleForm.clearValidate(); // 清除验证提示

          ////console.log("this.cleanform.dynamicItem",this.cleanform.dynamicItem)
        } else {
          this.$message({
            type: "error",
            message: "清洗规则查询失败" + res.Message,
          });
        }
      });
    },
    //调试脚本
    async validateInputs() {
      const validationResults = await this.tableDataInput.reduce(
        async (accumulatorPromise, _, j) => {
          const accumulator = await accumulatorPromise;
          if (!accumulator) {
            return false; // Short-circuit if any previous validation failed
          }

          const validSingle =
            this.$refs.inputValue_0.validateMessage == undefined ||
            this.$refs.inputValue_0.validateMessage == "";

          return accumulator && validSingle;
        },
        Promise.resolve(true)
      );

      return validationResults;
    },

    async CleanScriptDebugging() {
      if (this.cleanform.codeInput == "") {
        return this.$message({
          type: "error",
          message: "脚本内容不可为空！",
        });
      }
      const isValid = await this.validateInputs();
      if (isValid) {
        this.cleanform.codeOutput = "";
        const param = {
          ScriptContent: this.cleanform.codeInput,
          OutputType: this.cleanform.outputType,
          ParameterInformations: [],
        };

        for (let i = 0; i < this.tableDataInput.length; i++) {
          if (
            this.tableDataInput[i].inputValue == "" &&
            this.tableDataInput[i].dataType != "String"
          ) {
            return this.$message({
              type: "error",
              message: "输入参数无效！",
            });
          }
          const parameterInformation = {
            Value: this.tableDataInput[i].inputValue,
            DataType: this.variableType.find(
              (item) => item.name === this.tableDataInput[i].dataType
            ).value,
          };
          param.ParameterInformations.push(parameterInformation);
        }

        try {
          const res = await $http.post(`/EqManage/CleanScriptDebugging`, param);
          if (res.Data) {
            this.cleanform.codeOutput = res.Data;
            this.isCodeValid = true;
            this.errorMessage = "";
          } else {
            this.isCodeValid = false;
            this.errorMessage = res.Message;
            this.$message({
              type: "error",
              message: res.Message,
            });
          }
        } catch (error) {
          console.log(error);
        }
      } else {
        this.$message({
          type: "error",
          message: "输入参数无效！",
        });
      }
    },
    //调试脚本

    //清洗规则输入框校验
    // 根据数据类型定义输入值的验证规则
    getValidationRules(row) {
      if (row.dataType === "Boolean") {
        return {
          inputValue: [
            { required: true, message: "请输入布尔值", trigger: "blur" },
            { validator: this.validateBooleanInput, trigger: "blur" },
          ],
        };
      } else if (row.dataType === "SByte") {
        return {
          inputValue: [
            { required: true, message: "请输入SByte类型的值", trigger: "blur" },
            { validator: this.validateSByteInput, trigger: "blur" },
          ],
        };
      } else if (row.dataType === "Byte") {
        return {
          inputValue: [
            { required: true, message: "请输入Byte类型的值", trigger: "blur" },
            { validator: this.validateByteInput, trigger: "blur" },
          ],
        };
      } else if (row.dataType === "Int16") {
        return {
          inputValue: [
            { required: true, message: "请输入Int16类型的值", trigger: "blur" },
            { validator: this.validateInt16Input, trigger: "blur" },
          ],
        };
      } else if (row.dataType === "UInt16") {
        return {
          inputValue: [
            {
              required: true,
              message: "请输入UInt16类型的值",
              trigger: "blur",
            },
            { validator: this.validateUInt16Input, trigger: "blur" },
          ],
        };
      } else if (row.dataType === "Int32") {
        return {
          inputValue: [
            { required: true, message: "请输入Int32类型的值", trigger: "blur" },
            { validator: this.validateInt32Input, trigger: "blur" },
          ],
        };
      } else if (row.dataType === "UInt32") {
        return {
          inputValue: [
            {
              required: true,
              message: "请输入UInt32类型的值",
              trigger: "blur",
            },
            { validator: this.validateUInt32Input, trigger: "blur" },
          ],
        };
      } else if (row.dataType === "Int64") {
        return {
          inputValue: [
            { required: true, message: "请输入Int64类型的值", trigger: "blur" },
            { validator: this.validateInt64Input, trigger: "blur" },
          ],
        };
      } else if (row.dataType === "UInt64") {
        return {
          inputValue: [
            {
              required: true,
              message: "请输入UInt64类型的值",
              trigger: "blur",
            },
            { validator: this.validateUInt64Input, trigger: "blur" },
          ],
        };
      } else if (row.dataType === "Float") {
        return {
          inputValue: [
            { required: true, message: "请输入Float类型的值", trigger: "blur" },
            { validator: this.validateFloatInput, trigger: "blur" },
          ],
        };
      } else if (row.dataType === "Double") {
        return {
          inputValue: [
            {
              required: true,
              message: "请输入Double类型的值",
              trigger: "blur",
            },
            { validator: this.validateDoubleInput, trigger: "blur" },
          ],
        };
      } else if (row.dataType === "Bytes") {
        return {
          inputValue: [
            { required: true, message: "请输入Bytes类型的值", trigger: "blur" },
            { validator: this.validateBytesInput, trigger: "blur" },
          ],
        };
      } else {
        return {}; // 对于其他数据类型，不设置验证规则
      }
    },

    getInputValueValidationRules(row) {
      if (row.dataType === "Boolean") {
        return { validator: this.validateBooleanInput };
      } else if (row.dataType === "SByte") {
        return { validator: this.validateSByteInput };
      } else if (row.dataType === "Byte") {
        return { validator: this.validateByteInput };
      } else if (row.dataType === "Int16") {
        return { validator: this.validateInt16Input };
      } else if (row.dataType === "UInt16") {
        return { validator: this.validateUInt16Input };
      } else if (row.dataType === "Int32") {
        return { validator: this.validateInt32Input };
      } else if (row.dataType === "UInt32") {
        return { validator: this.validateUInt32Input };
      } else if (row.dataType === "Int64") {
        return { validator: this.validateInt64Input };
      } else if (row.dataType === "UInt64") {
        return { validator: this.validateUInt64Input };
      } else if (row.dataType === "Float") {
        return { validator: this.validateFloatInput };
      } else if (row.dataType === "Double") {
        return { validator: this.validateDoubleInput };
      } else if (row.dataType === "Bytes") {
        return { validator: this.validateBytesInput };
      } else {
        return {}; // 对于其他数据类型，不设置自定义校验函数
      }
    },
    // 自定义校验函数：布尔类型的输入值只能为true或false
    validateBooleanInput(rule, value, callback) {
      const lowerCaseValue = value.toLowerCase();
      if (lowerCaseValue !== "true" && lowerCaseValue !== "false") {
        callback(new Error("只能为 true 或 false"));
      } else {
        callback();
      }
    },
    // 自定义校验函数：SByte类型的输入值必须是有效的SByte
    validateSByteInput(rule, value, callback) {
      if (value == "") {
        callback(new Error("请输入SByte类型的值"));
      } else if (
        !Number.isInteger(Number(value)) ||
        value < -128 ||
        value > 127
      ) {
        callback(new Error("请输入SByte类型的值"));
      } else {
        callback();
      }
    },
    // 自定义校验函数：Byte类型的输入值必须是有效的Byte
    validateByteInput(rule, value, callback) {
      if (value == "") {
        callback(new Error("请输入Byte类型的值"));
      } else if (!Number.isInteger(Number(value)) || value < 0 || value > 255) {
        callback(new Error("请输入Byte类型的值"));
      } else {
        callback();
      }
    },
    // 自定义校验函数：Int16类型的输入值必须是有效的Int16
    validateInt16Input(rule, value, callback) {
      if (value == "") {
        callback(new Error("请输入Int16类型的值"));
      } else if (
        !Number.isInteger(Number(value)) ||
        value < -32768 ||
        value > 32767
      ) {
        callback(new Error("请输入Int16类型的值"));
      } else {
        callback();
      }
    },
    // 自定义校验函数：UInt16类型的输入值必须是有效的UInt16
    validateUInt16Input(rule, value, callback) {
      if (value == "") {
        callback(new Error("请输入UInt16类型的值"));
      } else if (!Number.isInteger(value) || value < 0 || value > 65535) {
        callback(new Error("请输入UInt16类型的值"));
      } else {
        callback();
      }
    },
    // 自定义校验函数：Int32类型的输入值必须是有效的Int32
    validateInt32Input(rule, value, callback) {
      if (value == "") {
        callback(new Error("请输入Int32类型的值"));
      } else if (
        !Number.isInteger(Number(value)) ||
        value < -2147483648 ||
        value > 2147483647
      ) {
        callback(new Error("请输入Int32类型的值"));
      } else {
        callback();
      }
    },
    // 自定义校验函数：UInt32类型的输入值必须是有效的UInt32
    validateUInt32Input(rule, value, callback) {
      if (value === "") {
        callback(new Error("请输入UInt32类型的值"));
      } else if (
        !Number.isInteger(Number(value)) ||
        value < 0 ||
        value > 4294967295
      ) {
        callback(new Error("请输入UInt32类型的值"));
      } else {
        callback();
      }
    },
    // 自定义校验函数：Int64类型的输入值必须是有效的Int64
    validateInt64Input(rule, value, callback) {
      if (value == "") {
        callback(new Error("请输入Int64类型的值"));
      } else if (
        !Number.isInteger(Number(value)) ||
        value < -9223372036854775808 ||
        value > 9223372036854775807
      ) {
        callback(new Error("请输入Int64类型的值"));
      } else {
        callback();
      }
    },
    // 自定义校验函数：UInt64类型的输入值必须是有效的UInt64
    validateUInt64Input(rule, value, callback) {
      if (value === "") {
        callback(new Error("请输入UInt64类型的值"));
      } else if (
        !Number.isInteger(Number(value)) ||
        value < 0 ||
        value > 18446744073709551615
      ) {
        callback(new Error("请输入UInt64类型的值"));
      } else {
        callback();
      }
    },
    // 自定义校验函数：Float类型的输入值必须是有效的Float
    validateFloatInput(rule, value, callback) {
      const parsedValue = parseFloat(value);
      if (
        isNaN(parsedValue) ||
        !isFinite(parsedValue) ||
        typeof parsedValue !== "number"
      ) {
        callback(new Error("请输入Float类型的值"));
      } else {
        callback();
      }
    },
    // 自定义校验函数：Double类型的输入值必须是有效的Double
    validateDoubleInput(rule, value, callback) {
      const parsedValue = parseFloat(value);
      if (
        isNaN(parsedValue) ||
        !isFinite(parsedValue) ||
        typeof parsedValue !== "number"
      ) {
        callback(new Error("请输入Double类型的值"));
      } else {
        callback();
      }
    },
    // 自定义校验函数：Bytes类型的输入值必须是有效的Bytes
    validateBytesInput(rule, value, callback) {
      if (
        !Array.isArray(value) ||
        !value.every(
          (item) => Number.isInteger(Number(value)) && item >= 0 && item <= 255
        )
      ) {
        callback(new Error("请输入Bytes类型的值"));
      } else {
        callback();
      }
    },
    //清洗规则输入框校验

    //获取所有输入参数
    getAllInputAliasOptions() {},
    //获取所有输入参数

    //增加输入参数
    addItem(form) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          if (this.tableDataInput.length >= 10) {
            this.$message({
              type: "error",
              message: "输入参数的最大数量为10！",
            });
            return;
          }
          if (
            this.tableDataInput.some(
              (item) => item.param === this.cleanform.inputName
            )
          ) {
            this.$message({
              type: "error",
              message: "同一参数不可重复添加！",
            });
            return;
          }

          this.cleanform.dynamicItem.push({
            name: this.cleanform.inputName,
          });
          // 寻找inputAliasOptions中名字等于this.cleanform.inputName
          let foundItem = this.findItem(this.inputAliasOptions);
          //debugger;
          let typeName = this.variableType.find(
            (item) => item.value == foundItem.type
          ).name;

          this.tableDataInput.push({
            param: this.cleanform.inputName,
            dataType: typeName,
            inputValue: "",
            id: foundItem.id,
            index: foundItem.index,
          });
          //console.log(this.tableDataInput);
          this.cleanform.inputName = "";
        } else {
          return;
        }
      });
    },
    //增加输入参数

    //保存清洗规则
    saveCleanRuleBaseInfoCheck() {
      if (this.cleanform.codeInput == "") {
        this.$confirm("当前脚本内容为空,确认取消清洗吗?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          this.saveCleanRuleBaseInfo();
        });
      } else {
        if (this.cleanform.dynamicItem.length > 0) {
          this.saveCleanRuleBaseInfo();
        } else {
          this.$message({
            type: "error",
            message: "请设置输入参数！",
          });
          return false;
        }
      }
    },
    //保存清洗规则
    saveCleanRuleBaseInfo() {
      let param = {
        InputParamInfos: [],
        ScriptContent: this.cleanform.codeInput,
        OutParamInfo: {
          OutputParamName: this.cleanform.output,
          OutputParamType: this.cleanform.outputType,
        },
        CleanedParamName: this.cleanform.cleanedParamName,
        PLCID: this.node.StructGuid,
        CleanedParamId: this.cleanform.cleanedParamId,
        ID: 0,
        CleanedParamType: 0,
        Index: this.cleanform.index,
      };
      for (let i = 0; i < this.tableDataInput.length; i++) {
        let parameterInformation = {
          InputParamName: this.tableDataInput[i].param,
          IsArray: this.tableDataInput[i].index != -1,
          InputParamId: this.tableDataInput[i].id,
          Index: this.tableDataInput[i].index,
          InputParamType: 0,
          InputParamVariableType: this.variableType.find(
            (item) => item.name == this.tableDataInput[i].dataType
          ).value,
        };
        param.InputParamInfos.push(parameterInformation);
      }

      $http.post(`/EqManage/CleanScriptUpdate`, param).then((res) => {
        if (res.Status == 200) {
          this.$message({
            type: "success",
            message: "清洗规则保存成功！",
          });
          this.dataCleanSettingDialogVisable = false;
          // 在需要清除验证状态的地方
          this.expandHandle();
          this.selectPlcVar();

          this.clearTableValidation();
        } else {
          this.$message({
            type: "error",
            message: "清洗规则保存失败" + res.Message,
          });
        }
      });
    },
    findItem(options) {
      const foundItem = options.find(
        (item) => item.label == this.cleanform.inputName
      );
      if (foundItem) {
        return foundItem;
      }

      for (const option of options) {
        if (option.children && option.children.length > 0) {
          const foundChild = this.findItem(option.children);
          if (foundChild) {
            return foundChild;
          }
        }
      }

      return null;
    },
    //保存清洗规则

    //删除输入参数
    deleteItem(item, index) {
      if (index == 0) {
        return this.$message({
          type: "error",
          message: "被清洗的变量不可被删除",
        });
      }
      this.cleanform.dynamicItem.splice(index, 1);
      this.tableDataInput.splice(index, 1);
    },
    //删除输入参数

    testConsole(param) {
      //console.log("测试打印参数", param);
    },
    confirmImport(type) {
      this.$confirm("此操作导入采集变量, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          if (type == "plc") {
            let param = {
              plcId: this.node.StructGuid,
              importData: this.importContent,
            };
            $http
              .post(`/EqManage/ImportPlcVariable`, param)
              .then((res) => {
                if (res.Data) {
                  this.selectPlcVar();
                  this.importVisable = false;
                  this.$message({
                    type: "success",
                    message: "导入采集变量成功",
                  });
                } else {
                  this.selectPlcVar();
                  this.$message({
                    type: "error",
                    message: res.Message,
                  });
                }
              })
              .catch((error) => {
                this.$message({
                  type: "error",
                  message: "导入文件格式或内容不正确",
                });
              });
          } else if (type == "eq") {
            let param = {
              eqId: this.node.StructGuid,
              importData: this.importContent,
            };
            $http
              .post(`/EqManage/ImportEqTree`, param)
              .then((res) => {
                if (res.Data) {
                  this.importVisable = false;
                  this.selectPlcVar();
                  this.$message({
                    type: "success",
                    message: "导入设备全部配置成功",
                  });
                } else {
                  this.selectPlcVar();
                  this.$message({
                    type: "error",
                    message: res.Message,
                  });
                }
              })
              .catch((error) => {
                this.$message({
                  type: "error",
                  message: "导入文件格式或内容不正确",
                });
              });
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消导入",
          });
        });
    },
    openCSV(id, name) {
      if (this.fahtherChecked) {
        this.$confirm("此操作导出采集变量, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            if (this.fahtherChecked.length > 0) {
              $http
                .post(
                  `/EqManage/BatchDownPlcData`,
                  JSON.parse(JSON.stringify(this.fahtherChecked))
                )
                .then((res) => {
                  if (res) {
                    const url = window.URL.createObjectURL(
                      new Blob([res], { type: "text/json" })
                    );
                    const link = document.createElement("a");
                    link.href = url;
                    link.setAttribute("download", `${name}.json`);
                    document.body.appendChild(link);
                    link.click();
                  } else {
                    this.$message({
                      type: "error",
                      message: "导出部件变量失败",
                    });
                  }
                })
                .catch((error) => {
                  //debugger;
                  this.$message({
                    type: "error",
                    message: `${error.response.data.Message}`,
                  });
                });
            } else {
              $http
                .get(`/EqManage/DownLoadPlcData?id=${id}`, {
                  responseType: "blob",
                })
                .then((res) => {
                  if (res) {
                    const url = window.URL.createObjectURL(
                      new Blob([res], { type: "application/vnd.ms-excel" })
                    );
                    const link = document.createElement("a");
                    link.href = url;
                    link.setAttribute("download", `${name}.xlsx`);
                    document.body.appendChild(link);
                    link.click();
                  } else {
                    this.$message({
                      type: "error",
                      message: "导出部件变量失败",
                    });
                  }
                })
                .catch((error) => {
                  this.$message({
                    type: "error",
                    message: `${error.response.data.Message}`,
                  });
                });
            }
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消导出",
            });
          });
      } else {
        this.$confirm("此操作导出部件变量, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            $http
              .get(`/EqManage/DownLoadPlcData?id=${id}`, {
                responseType: "blob",
              })
              .then((res) => {
                if (res) {
                  const url = window.URL.createObjectURL(
                    new Blob([res], { type: "text/json" })
                  );
                  const link = document.createElement("a");
                  link.href = url;
                  link.setAttribute("download", `${name}.json`);
                  document.body.appendChild(link);
                  link.click();
                } else {
                  this.$message({
                    type: "error",
                    message: "导出部件变量失败",
                  });
                }
              });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消导出",
            });
          });
      }
    },
    addfile(files, fileList) {
      if (fileList.length > 1) {
        fileList.splice(0, 1);
      }
      this.fileList = fileList;
      //console.log(files);
      //console.log(fileList);
      let file = fileList[0];
      console.log("file", file);
      console.log(file.name);

      if (file.name.substring(file.name.lastIndexOf(".") + 1) != "xlsx") {
        this.$message.error("变量导入失败，文件格式不正确，请使用xlsx格式文件");
        return;
      }
      let reader = new FileReader();
      reader.readAsBinaryString(file.raw);
      reader.onload = (e) => {
        // 读取文件内容
        const fileString = e.target.result;

        let excel = XLSX.read(fileString, { type: "binary" });
        let sheetname = excel.SheetNames[0];
        let sheet = excel.Sheets[sheetname];
        // delete sheet.A1;
        // 接下来可对文件内容进行处理
        this.importContent = JSON.stringify(
          XLSX.utils.sheet_to_json(sheet, { range: 2 })
        );

        this.importBtn = true;
      };
    },
    mergeDuplicates(array, item) {
      // 检查数组中是否已存在相同的项
      const index = array.findIndex((element) => {
        // 这里假设数组中的元素是对象，且对象具有唯一的标识属性，比如'id'
        return element.Alias === item.Alias;
      });

      if (index !== -1) {
        // 如果存在相同的项，进行合并操作
        array[index] = this.mergeItems(array[index], item);
      } else {
        // 如果不存在相同的项，直接将新项添加到数组中
        array.push(item);
      }
    },
    mergeItems(existingItem, newItem) {
      // 这里假设将两个对象的属性进行合并
      return {
        ...existingItem,
        ...newItem,
      };
    },
    sonHandleSelectionChange(event) {
      //console.log("操作子级选中", event);
      event.forEach((m) => {
        this.mergeDuplicates(this.sonChecked, m);
      });

      //console.log("打印子级", this.sonChecked);
    },
    /**
     * 只允许展开一行
     * @param {*} row
     */
    expandOnlyRows(row) {
      if (this.expandedRowKeys.length > 0) {
        const index = this.expandedRowKeys.indexOf(row.ID);
        //console.log("index", index);
        if (index != -1) {
          this.expandedRowKeys.splice(index, 1);
        } else {
          this.expandedRowKeys.splice(0, this.expandedRowKeys.length);
          this.expandedRowKeys.push(row.ID);
        }
      } else {
        this.expandedRowKeys.push(row.ID);
      }
      console.log("this.expandedRowKeys", this.expandedRowKeys);
    },
    // 树形表格展开时
    expandValue(event, obj) {
      this.expandOnlyRows(event);
      this.expandEvent = event;
      this.expandObj = obj;
      this.expandHandle();
    },
    expandHandle() {
      this.expandLoading = true;
      let event = this.expandEvent;
      let obj = this.expandObj;

      let param = {
        alias: "",
        name: "",
        currPage: this.sonPageNum,
        id: event.ID,
        monitoredState: 0,
        dataType: 0,
        persistenceState: 0,
        isCleaned: this.isCleaned,
      };

      let isDifferent = false;
      for (let key in param) {
        if (
          key !== "currPage" &&
          JSON.stringify(param[key]) !==
            JSON.stringify(this.searchSonConditionLast[key])
        ) {
          isDifferent = true;
          break;
        }
      }

      if (isDifferent) {
        this.sonPageNum = 1;
        param.currPage = 1;
      }

      this.searchSonConditionLast = param;
      console.log("1111", obj);
      if (obj && obj.length > 0) {
        $http
          .post(`/EqManage/PlcArrayDataExpand`, param)
          .then((res) => {
            if (res.Data != null) {
              //将数据加入到需要的集合中
              this.sonTotal = res.Data.totalCount;
              this.expandArray.splice(
                this.expandArray.findIndex((m) => m.id == event.ID),
                1,
                { id: event.ID, data: res.Data.pageData }
              );
              this.expandLoading = false;
            } else {
              this.expandLoading = false;
            }
          })
          .catch((err) => {
            //console.log(err);
            this.expandLoading = false;
          });
      }
    },

    getRowExpandData(id, exArray) {
      let param = [];
      //console.log("数据到位,打印this", this);
      let res = exArray.find((m) => m.id.isEqualTo(id));
      if (res) {
        param = res.data;
        // res.data.forEach((m) => {
        //   this.$refs[`sontable${id}`].toggleRowSelection(m, true);
        // });
      }
      //选中子项所有项
      return param;
    },

    checkedBoxHandler(event, obj) {
      this.fahtherChecked = event;
      //console.log("单勾选", event, obj); //单钩选时，要勾选下一级，或取消下一级
      if (obj && obj.IsArray) {
        //是数组才操作下一级，否则不需要操作
        if (event.includes(obj)) {
          //console.log("选中下一级");
          //console.log("确认this", this);
        } else {
          //console.log("取消下一级");
        }
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    fatherSelectAllHandler(event) {
      //console.log("111", event);
      this.fahtherChecked = event;
      //全选时要选中所有级别,或取消所有级别
    },
    getRowKeys(row) {
      return String(row.ID);
    },
    getRowClass(row, index) {
      if (!row.row.IsArray) {
        return "row-expand-cover";
      }
      //即改行没有子元素时，添加row-expand-cover类
    },

    handconsole(param) {
      //console.log(param);
    },
    addPlcVar(form) {
      this.$refs.plcVarFormRef.validate((valid) => {
        if (!valid) {
          this.$message.error("填写数据格式不正确");
        } else {
          $http.post(form.Url, form).then((res) => {
            if (res.Data != null) {
              this.$message({
                type: "success",
                message: form.Title + "成功",
              });
              this.plcVarVisable = false;
              this.selectPlcVar();
            } else {
              if (res.Message) {
                this.$message({
                  type: "error",
                  message: form.Title + "失败," + res.Message,
                });
              }
            }
          });
        }
      });
      // this.$refs.plcVarForm.resetFields(); //重置表单验证
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.selectPlcVar();
    },
    fatherCurrentChange(val) {
      this.pageNum = val;
      this.selectPlcVar();
    },
    handleCurrentChange(val) {
      this.sonPageNum = val;
      this.expandHandle();
    },
    dataToPlc(key) {
      //console.log("key", key);
      return this.variableType.find((m) => m.value == key).name;
    },
    // 刷新采集变量表
    selectPlcVar(obj) {
      let param = {
        pageSize: this.pageSize,
        currentPage: this.pageNum,
        plcId: obj ? obj : this.node.StructGuid,
        alias: this.alias,
        name: this.name,
        isMonitored: this.isMonitored,
        isCleaned: this.isCleaned,
      };

      let isDifferent = false;
      for (let key in param) {
        if (
          key !== "currentPage" &&
          JSON.stringify(param[key]) !==
            JSON.stringify(this.searchConditionLast[key])
        ) {
          isDifferent = true;
          break;
        }
      }

      if (isDifferent) {
        this.pageNum = 1;
        param.currentPage = this.pageNum;
      }
      this.searchConditionLast = param;

      $http
        .post("/EqManage/GetPlcVar", param)
        .then((res) => {
          if (res.Data) {
            let map = new Map();
            let uniqueArray = res.Data.pageData.filter((obj) => {
              if (!map.has(obj.Alias)) {
                map.set(obj.Alias, true);
                return true;
              }
              return false;
            });
            this.plcValTable = uniqueArray;
            this.inputAliasOptions = [];
            for (let j = 0; j < this.plcValTable.length; j++) {
              if (this.plcValTable[j].IsArray) {
                this.inputAliasOptions.push({
                  value:
                    this.plcValTable[j].PlcName +
                    "." +
                    this.plcValTable[j].Alias,
                  label:
                    this.plcValTable[j].PlcName +
                    "." +
                    this.plcValTable[j].Alias,
                  type: this.plcValTable[j].DataTypeId,
                  id: this.plcValTable[j].ID,
                  index: -1,
                  children: [],
                });
              } else {
                this.inputAliasOptions.push({
                  value:
                    this.plcValTable[j].PlcName +
                    "." +
                    this.plcValTable[j].Alias,
                  label:
                    this.plcValTable[j].PlcName +
                    "." +
                    this.plcValTable[j].Alias,
                  type: this.plcValTable[j].DataTypeId,
                  id: this.plcValTable[j].ID,
                  index: -1,
                });
              }
            }

            for (let i = 0; i < this.inputAliasOptions.length; i++) {
              if (this.inputAliasOptions[i].children) {
                let paramArray = {
                  alias: "",
                  name: "",
                  currPage: 1,
                  id: this.inputAliasOptions[i].id,
                  monitoredState: 0,
                  dataType: 0,
                  persistenceState: 0,
                };

                $http
                  .post(`/EqManage/PlcArrayDataExpand`, paramArray)
                  .then((res) => {
                    if (res.Data != null) {
                      this.inputAliasOptions[i].children =
                        res.Data.pageData.map((item) => ({
                          value: item.PlcName + "." + item.Alias,
                          label: item.PlcName + "." + item.Alias,
                          id: this.inputAliasOptions[i].id,
                          index: item.Index,
                          type: item.DataTypeId,
                        }));
                    }
                  });
              }
            }

            this.tstdata = this.plcValTable[0];
            this.total = res.Data.totalCount;
          } else {
            this.plcValTable = [];
            this.total = 0;
          }
        })
        .catch((err) => {
          this.$message.error("查询采集变量失败" + err);
        });
    },
    LoadPlcVar(tree, treeNode, resolve) {
      //存在子节点就map，否则生成新的子节点，更新的时候加入数据库
      let param = "";
      let objCollection = [];
      let newArray = "";
      for (let i = 0; i < tree.ArrayLength; i++) {
        objCollection.push({
          ID: tree.ID,
          PlcID: tree.PlcID,
          Name: tree.Name + "[" + i + "]",
          Alias: tree.Alias + "[" + i + "]",
          BizType: tree.BizType,
          DataTypeId: tree.DataTypeId,
          IsArray: null,
          ArrayStartIndex: 0,
          ArrayEndIndex: 0,
          ArrayLength: 0,
          IsMonitored: false,
          IsRw: 0,
          ScanPeriod: 0,
          MonitorInfo: "",
          Description: "",
        });
      }
      if (tree.MonitorInfo) {
        param = JSON.parse(tree.MonitorInfo);

        let newarray = param.map((par) => {
          return {
            ID: tree.ID,
            DataType: tree.DataType,
            Alias: tree.Alias + "[" + par.index + "]",
            IsMonitored: par.isMonitored,
            Description: par.desc,
            ScanPeriod: par.scanPeriod,
            InitValue: par.initValue,
          };
        });
        newArray = objCollection.map((obj) => {
          const newObj = newarray.find((newObj) => newObj.Alias === obj.Alias);
          if (newObj) {
            return newObj;
          } else {
            return obj;
          }
        });
      } else {
        newArray = objCollection;
      }
      //debugger;
      resolve(newArray);
    },
    //过滤选中的子节点
    filterSon() {
      let father = this.fahtherChecked;
      let son = this.sonChecked;
      //去掉在父类下的子元素
      let sonRes = son.filter(
        (sonItem) =>
          !father.some((fatherItem) =>
            sonItem.ParentId.isEqualTo(fatherItem.ID)
          )
      );
      return { father, sonRes };
    },
    /**
     * 批量加入监控
     * @param {*} form
     */
    AllAddMonitored(form) {
      if (form) {
        //debugger
        if (form.isMonitored) {
          this.$refs.allmonitoredForm.validate((valid) => {
            if (!valid) {
              return;
            } else {
              if (
                this.fahtherChecked.length === 0 &&
                this.sonChecked.length == 0
              ) {
                this.$message.error("请至少选择一个变量");
                return;
              }
              let value = form.isMonitored;

              //去掉已加入监控的非数组
              // let father = this.fahtherChecked.filter(
              //   (m) => !(m.IsArray == true && m.IsMonitored == value)
              // );
              //去掉已加入监控的子级元素
              // let son = this.sonChecked.filter(
              //   (m) => !(m.IsArray == true && m.IsMonitored == value)
              // );

              //let fatherRes = [];

              // for (var i = 0; i < father.length; i++) {
              //   if (
              //     !son.some(
              //       (m) => JSON.stringify(m.ParentId) == JSON.stringify(father[i].ID)
              //     )
              //   ) {
              //     debugger;
              //     fatherRes.push(father[i]);
              //   }
              // }
              //去掉子级存在，同时父级存在的情况
              // let fatherRes = father.filter(
              //   (itemA) =>
              //     !son.some(
              //       (itemB) =>
              //         JSON.stringify(itemA.ID) == JSON.stringify(itemB.ParentId)
              //     )
              // );

              const fs = this.filterSon();

              $http
                .post(
                  "/EqManage/BatchMonitor",

                  {
                    ParentList: fs.father,
                    ChildList: fs.sonRes,
                    IsMonitorChecked: value,
                    ScanPeriod: form.scanPeriod,
                  }
                )
                .then((res) => {
                  if (res.Data) {
                    this.fahtherChecked = [];
                    this.sonChecked = [];
                    this.$message.success(
                      value ? "批量加入监控成功" : "批量取消监控成功"
                    );
                    this.alladdMonitoredVisable = false;
                    this.expandHandle();
                    this.selectPlcVar();
                    this.$refs.multipleTable.clearSelection();
                  } else {
                    this.$confirm(
                      `${res.Message}`,
                      value ? "批量加入监控失败" : "批量取消监控失败",
                      {
                        confirmButtonText: "确定",
                        showCancelButton: false, //是否显示关闭按钮
                        type: "error",
                      }
                    );
                    this.expandHandle();
                    this.selectPlcVar();
                    this.$refs.multipleTable.clearSelection();
                  }
                  //刷新变量栏目
                })
                .catch((err) => {
                  this.$message.error(`${err}`);
                });
            }
          });
        } else {
          if (
            this.fahtherChecked.length === 0 &&
            this.sonChecked.length === 0
          ) {
            this.$message.error("请至少选中一个节点");
            return;
          }
          let value = form.isMonitored;
          //去掉已加入监控的非数组
          // let father = this.fahtherChecked.filter(
          //   (m) => !(m.IsArray == true && m.IsMonitored == value)
          // );
          //去掉已加入监控的子级元素
          // let son = this.sonChecked.filter(
          //   (m) => !(m.IsArray == true && m.IsMonitored == value)
          // );

          //let fatherRes = [];

          // for (var i = 0; i < father.length; i++) {
          //   if (
          //     !son.some(
          //       (m) => JSON.stringify(m.ParentId) == JSON.stringify(father[i].ID)
          //     )
          //   ) {
          //     debugger;
          //     fatherRes.push(father[i]);
          //   }
          // }
          //去掉子级存在，同时父级存在的情况
          // let fatherRes = father.filter(
          //   (itemA) =>
          //     !son.some(
          //       (itemB) =>
          //         JSON.stringify(itemA.ID) == JSON.stringify(itemB.ParentId)
          //     )
          // );
          const fs = this.filterSon();
          $http
            .post(
              "/EqManage/BatchMonitor",

              {
                ParentList: fs.father,
                ChildList: fs.sonRes,
                IsMonitorChecked: value,
                ScanPeriod: form.scanPeriod,
              }
            )
            .then((res) => {
              if (res.Data) {
                this.fahtherChecked = [];
                this.sonChecked = [];
                this.$message.success(
                  value ? "批量加入监控成功" : "批量取消监控成功"
                );
                this.alladdMonitoredVisable = false;
                this.expandHandle();
                this.selectPlcVar();
                this.$refs.multipleTable.clearSelection();
              } else {
                this.$confirm(
                  `${res.Message}`,
                  value ? "批量加入监控失败" : "批量取消监控失败",
                  {
                    confirmButtonText: "确定",
                    showCancelButton: false, //是否显示关闭按钮
                    type: "error",
                  }
                );
                this.expandHandle();
                this.selectPlcVar();
                this.$refs.multipleTable.clearSelection();
              }
              //刷新变量栏目
            })
            .catch((err) => {
              this.$message.error(`${err}`);
            });
        }
      }
    },

    //判断整理加入监控的数组和非数组，去重

    DeletePlcVar(obj) {
      this.$confirm("此操作删除采集变量, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() =>
          $http.get(`/EqManage/DeleteVar?id=${obj}`).then((res) => {
            if (res.Data) {
              this.$message.success("删除采集变量成功");
              this.selectPlcVar();
            } else {
              this.$message({
                type: "error",
                message: res.Message,
              });
            }
            //刷新变量栏目
          })
        )
        .catch((err) => {
          this.$message.error(err);
        });
    },

    DeleteAllVar() {
      this.$confirm("此操作批量删除采集变量, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          $http
            .post(
              "/EqManage/BatchDelete",
              JSON.parse(JSON.stringify(this.fahtherChecked))
              // { Arrays: JSON.stringify(this.fahtherChecked) }
              //this.fahtherChecked
            )
            .then((res) => {
              if (res.Data) {
                this.$message.success("批量删除采集变量成功");
                this.selectPlcVar();
              } else {
                this.$message({
                  type: "error",
                  message: res.Message,
                });
              }
              //刷新变量栏目
            });
        })
        .catch((err) => {
          debugger;
          this.$message.error(err);
        });
    },
    DeletePlcVarList() {
      this.$confirm("此操作删除采集变量, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let idList = this.$refs.xTree.getCheckboxRecords(false);

          let s = $base.Base64.encodeURL(stringify(idList));
          //console.log();
          //debugger;
          $http
            .post("/EqManage/DeletePlcVarList", { Arrays: s })
            .then((res) => {
              if (res.Data) {
                this.$message.success("删除采集变量成功");
                this.selectPlcVar();
              } else {
                this.$message({
                  type: "error",
                  message: res.Message,
                });
              }
              //刷新变量栏目
            });
        })
        .catch((err) => {
          this.$message.error(err);
        });
      // let selectRow = this.$refs.xTree.getCheckboxRecords(false);
      // //console.log(selectRow);
      // //console.log(this.$refs.xTree.getData());
      // //console.log(this.$refs.xTree);
    },

    AddMonitored(form) {
      if (form) {
        if (form.isMonitored) {
          this.$refs.monitoredForm.validate((valid) => {
            if (!valid) {
              return;
            } else {
              // this.monitoredForm.scanPeriod =
              //   this.monitoredForm.scanPeriod / 100;
              let table = this.$refs.multipleTable;
              $http
                .post(form.Url, form)
                .then((res) => {
                  if (res.Data) {
                    //this.processOption = res.Data.pageData
                    if (form.Update) {
                      this.expandHandle();
                    } else {
                      this.selectPlcVar();
                    }
                    // this.expandHandle();
                    // this.selectPlcVar();
                    //this.$refs.multipleTable.clearSelection();
                    this.addMonitoredVisable = false;
                    this.$message.success(form.Title + "成功");
                  } else {
                    this.$confirm(`${res.Message}`, "变量加入监控操作失败", {
                      confirmButtonText: "确定",
                      showCancelButton: false, //是否显示关闭按钮
                      type: "error",
                    });
                  }
                })
                .catch((err) => {
                  this.$message.error(form.Title + "失败" + err);
                });
            }
          });
        } else {
          this.monitoredForm.scanPeriod = 0;
          let table = this.$refs.multipleTable;
          $http
            .post(form.Url, form)
            .then((res) => {
              if (res.Data) {
                //this.processOption = res.Data.pageData
                if (form.Update) {
                  this.expandHandle();
                } else {
                  this.selectPlcVar();
                }
                this.addMonitoredVisable = false;
                this.$message.success(form.Title + "成功");
              } else {
                this.$confirm(`${res.Message}`, "变量取消监控操作失败", {
                  confirmButtonText: "确定",
                  showCancelButton: false, //是否显示关闭按钮
                  type: "error",
                });
              }
            })
            .catch((err) => {
              this.$message.error(form.Title + "失败" + err);
            });
        }
      } else {
        this.$message.error("操作监控状态失败");
      }
    },
    UpdateArrayDescript(form) {
      if (form) {
        let table = this.$refs.multipleTable;
        $http.post(form.Url, form).then((res) => {
          if (res.Data) {
            this.$message.success(form.Title + "成功");
            this.expandHandle();
          } else {
            this.$message.error(form.Title + "失败" + res.Message);
          }
        });
      } else {
        this.$message.error(form.Title + "失败");
      }
    },
    ExpandList() {
      //展开实时监控界面

      console.log("选中父级", this.fahtherChecked);
      console.log("选中子级", this.sonChecked);
      console.log("结果", this.filterSon());
      let res = this.filterSon();
      let param = [];
      //设置用户唯一ID
      this.userId = Date.now();
      this.varTableData = [];
      if (res.father && res.father.length > 0) {
        res.father.forEach((m) => {
          if (m.IsArray) {
            //如果父级数组选中，默认选中所有子级
            for (let i = 0; i < m.ArrayLength; i++) {
              this.varTableData.push({
                ID: m.ID,
                Index: i,
                IsArray: m.IsArray,
                Name: m.IsArray ? m.Alias + "[" + i + "]" : m.Alias,
                Description: m.Description,
                Value: "",
                OldValue: "",
                Time: "",
                UpdateTime: "",
              });
              param.push({ ID: m.ID, Index: i, UserID: String(this.userId) });
            }
          } else {
            this.varTableData.push({
              ID: m.ID,
              Index: m.Index,
              IsArray: m.IsArray,
              Name: m.IsArray ? m.Alias + "[" + m.Index + "]" : m.Alias,
              Description: m.Description,
              Value: "",
              OldValue: "",
              Time: "",
              UpdateTime: "",
            });
            param.push({
              ID: m.ID,
              Index: m.Index,
              UserID: String(this.userId),
            });
          }
        });
      } else if (res.sonRes) {
        res.sonRes.forEach((m) => {
          this.varTableData.push({
            ID: m.ParentId,
            Index: m.Index,
            IsArray: m.IsArray,
            Name: m.IsArray ? m.Alias + "[" + m.Index + "]" : m.Alias,
            Description: m.Description,
            Value: "",
            OldValue: "",
            Time: "",
            UpdateTime: "",
          });
          param.push({ ID: m.ID, Index: m.Index, UserID: String(this.userId) });
        });
      }
      if (this.fahtherChecked.length > 0 || this.sonChecked.length > 0) {
        $http.post("/EqManage/AddRealPlcVar", param).then((res) => {
          if (res.Data) {
            //开启rabbitmq接收
            //进行连接
            this.mqtthuoquMsg();
          } else {
            this.$message.error(`${res.Message}`);
          }
        });
      } else {
        this.$message.error("至少勾选一个要查看的采集变量");
      }
      //将选中的值存入redis

      //清空选中
      this.fahtherChecked = [];
      this.sonChecked = [];
      this.selectView = true;
    },
    DeleteRealPlcVar() {
      //删除redis中的键值，并关闭rabbitmq
      $http
        .get(`/EqManage/DeleteRealPlcVar?userId=${String(this.userId)}`)
        .then((res) => {
          if (res.Data) {
            //关闭rabbitmq接收
            this.close();
          } else {
            this.$message.error(`${res.Message}`);
          }
        });
    },
  },
  watch: {
    filterText(val) {
      if (val != "") {
        this.monitorDataTree = this.varTableDataAlways
          .filter((item) => item.Name.includes(val))
          .map((item) => ({
            id: item.Name,
            label: item.Name,
          }));
      } else {
        (this.monitorDataTree = [
          {
            id: 1,
            label: "全选",
            children: [],
          },
        ]),
          (this.monitorDataTree[0].children = this.varTableDataAlways.map(
            (item) => ({
              id: item.Name,
              label: item.Name,
            })
          ));
      }
    },
    filterText2(val) {
      if (val !== "") {
        const uniqueLabels = new Set();
        this.monitorDataDescTree = this.varTableDataAlways
          .filter((item) => {
            if (
              !uniqueLabels.has(item.Description) &&
              item.Description.includes(val)
            ) {
              uniqueLabels.add(item.Description);
              return true;
            }
            return false;
          })
          .map((item) => ({
            id: item.Description,
            label: item.Description,
          }));
      } else {
        this.monitorDataDescTree = [
          {
            id: 1,
            label: "全选",
            children: [],
          },
        ];

        const uniqueChildren = [];
        const uniqueLabels = new Set();

        this.varTableDataAlways.forEach((item) => {
          if (!uniqueLabels.has(item.Description)) {
            uniqueLabels.add(item.Description);
            uniqueChildren.push({
              id: item.Description,
              label: item.Description,
            });
          }
        });

        this.monitorDataDescTree[0].children = uniqueChildren;
      }
    },
  },
  computed: {
    displayScanPeriod() {
      return (scanPeriod) => {
        if (scanPeriod === 0) {
          return ""; // 当 ScanPeriod 为 0 时返回空字符串
        } else {
          return scanPeriod * 100; // 其他情况返回实际的 ScanPeriod 值
        }
      };
    },
  },
  beforeDestroy() {
    this.close();
  },
  async created() {},
};
</script>
<style  >
.row-expand-cover .el-table__expand-column .el-icon {
  visibility: hidden;
}
.scroller {
  height: 100%;
}

.user {
  height: 32%;
  padding: 0 12px;
  display: flex;
  align-items: center;
}

.dialog-container {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.bordered-row {
  border: 0.5px solid rgb(215, 218, 224); /* 这里的颜色和宽度可以根据需要进行调整 */
  padding: 10px; /* 可选：添加内边距来调整边框与内容之间的间距 */
}

.bordered-col {
  border: 0.5px solid rgb(215, 218, 224);
  padding: 10px;
}
.scrollable-div {
  border: 1px solid rgb(215, 218, 224); /* 设置边框样式 */
  height: 200px; /* 设置固定高度，可以根据需要进行调整 */
  overflow-y: auto; /* 添加垂直滚动条 */
}

.error-message {
  color: red;
}

.borderless-input .el-input__inner {
  border: none;
  background-color: transparent;
  box-shadow: none;
}

.CodeMirror {
  height: 500px;
}

.CodeMirror pre.CodeMirror-placeholder {
  color: #999;
  font-size: 0.5rem;
}
.import-icon {
  color: #606266;
  font-size: 14px;
}
.el-button--select {
  color: #fff;
  background-color: #8400ff;
  border-color: #8400ff;
}
.el-button--select.is-active,
.el-button--select:active {
  background: #430fff81;
  border-color: #430fff81;
  color: #fff;
  opacity: 0.5;
}
.el-button--select:focus {
  background: #8400f0;
  border-color: #8400f0;
  color: #fff;
}
.el-button--select:hover {
  background: #8400f0;
  border-color: #8400f0;
  color: #fff;
}
</style>